<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-col>
        <el-button type="primary">添加角色</el-button>

        <!-- 角色信息表单 -->
        <el-table :data="userRolesList" style="width: 100%" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 一级权限渲染 -->
              <el-row
                :gutter="20"
                v-for="(item1,index1) in scope.row.children"
                :key="item1.id"
                :class="['bdbottom',index1==0?'bdTop':'']"
              >
                <el-col :span="8">
                  <el-tag closable @close="removeById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="16">
                  <!-- 二级权限渲染 -->
                  <el-row
                    v-for="(item2,index2) in item1.children"
                    :key="item2.id"
                    :class="[index2===0?'':'bdTop']"
                  >
                    <el-col :span="8">
                      <el-tag
                        type="success"
                        closable
                        @close="removeById(scope.row,item2.id)"
                      >{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限渲染 -->
                    <el-col :span="16">
                      <!-- 三级标签直接循环的tag标签 -->
                      <el-tag
                        type="warning"
                        v-for="(item3) in item2.children"
                        :key="item3.id"
                        closable
                        @close="removeById(scope.row,item3.id)"
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="settingRight(scope.row)"
              >设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <!-- 点击设置弹出框 -->
      <el-dialog
        title="权限设置"
        :visible.sync="RightSettingdialogVisible"
        width="50%"
        @close="setRightsDialogClose"
      >
        <!-- 树形控件 -->
        <el-tree
          :data="rightList"
          show-checkbox
          node-key="id"
          :default-expanded-keys="[2, 3]"
          :default-checked-keys="defkeys"
          :props="treeprops"
          default-expand-all
          ref="treeRef"
        ></el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="RightSettingdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
export default {
  data() {
    return {
      userRolesList: [],
      // 权限设置
      RightSettingdialogVisible: false,
      // 用户的所有的权限数据
      rightList: [],
      // 属性控件的props属性
      treeprops: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认勾选的节点 存储的是所有三级权限的id
      defkeys: [],
      // 点击设置时获取对应的角色id
      role: ''
    };
  },
  methods: {
    async getUsersRolesList() {
      let { data: res } = await this.axios.get('roles');
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败');
      }
      this.userRolesList = res.data;
    },
    async removeById(role, id) {
      // console.log(role,id);
      // 提示用户是否确定要删除
      let result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err);
      console.log(result);
      if (result !== 'confirm') {
        return this.$message.error('已经取消删除');
      }
      // 发起该请求移除权限
      let { data: res } = await this.axios.delete(
        `roles/${role.id}/rights/${id}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('移除权限失败，请重试');
      }
      role.children = res.data;
      this.$message.success('移除权限成功');
    },
    async settingRight(role) {
      // 获取所有的权限数据
      this.role = role;
      let { data: res } = await this.axios.get('rights/tree');
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败');
      }
      this.rightList = res.data;
      // 递归获取所有三级借点的id
      this.getLeafTrees(role, this.defkeys);
      this.RightSettingdialogVisible = true;
    },
    // 获取所有三级借点的id
    getLeafTrees(node, arr) {
      if (!node.children) {
        // 如果不包含node.children则说明是三级借点 将idpush进去
        return arr.push(node.id);
      }
      // 如果包含了children
      node.children.forEach(item => {
        this.getLeafTrees(item, arr);
      });
    },
    setRightsDialogClose() {
      this.defkeys = [];
    },
    // 点击确定分配权限
    async allotRights() {
      // 获取所有的半选中的父节点的id以及选中的三级节点的id
      let keys = [];

      // 获取所有选中的三级借点的id
      const key1 = this.$refs.treeRef.getCheckedKeys();
      // 获取所有半选中的借点的id
      const key2 = this.$refs.treeRef.getHalfCheckedKeys();
      keys = [...key1, ...key2];
      console.log(keys);

      //  然后转化为一个已,分割的字符串，再发起请求
      const idstrs = keys.join(',');
      let { data: res } = await this.axios.post(
        `roles/${this.role.id}/rights`,
        {
          rids: idstrs
        }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('提交失败');
      }
      this.$message.success('提交成功');
      this.getUsersRolesList();
      this.RightSettingdialogVisible = false;
    }
  },
  mounted() {
    this.getUsersRolesList();
  }
};
</script>
<style scoped lang="less">
.el-card {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>